package com.easyfun.healthmagicbox.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import cn.kuaipan.android.openapi.KuaiPanManager;

import com.easyfun.healthmagicbox.R;
import com.easyfun.healthmagicbox.pojo.ConstantData;

import android.content.Context;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;

public class URIConverter {
	
	//@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	public static String getRealPathFromURI(Context mContext,Uri fileUrl) {
		String fileName = null;
		Uri filePathUri = fileUrl;
		if (fileUrl != null) {
			if (fileUrl.getScheme().toString().compareTo("content") == 0) // content://��ͷ��uri
			{
				Cursor cursor = mContext.getContentResolver().query(fileUrl,
						null, null, null, null);
				if (cursor != null && cursor.moveToFirst()) {
					int column_index = cursor
							.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
					fileName = cursor.getString(column_index); // ȡ���ļ�·��
					if (!fileName.startsWith("/mnt")) { // ����Ƿ��С�/mnt��ǰ׺
						fileName = "/mnt" + fileName;
					}
					//if (fileName.startsWith("/mnt")) { // ����Ƿ��С�/mnt��ǰ׺
					//	fileName = fileName.substring(4);
					//}
					cursor.close();
				}
			} else if (fileUrl.getScheme().compareTo("file") == 0) // file:///��ͷ��uri
			{
				fileName = filePathUri.toString().replace("file://", ""); // �滻file://
				//if (!fileName.startsWith("/mnt")) { // ����"/mnt"ͷ
				//	fileName += "/mnt";
				//}
			}
		}
		return fileName;
	}

	/*
	 * public String getRealPathFromURI(Uri contentUri) { { Uri uri =
	 * contentUri; String[] proj = { MediaStore.Images.Media.DATA }; Cursor
	 * actualimagecursor = managedQuery(uri,proj,null,null,null); int
	 * actual_image_column_index =
	 * actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
	 * actualimagecursor.moveToFirst(); String img_path =
	 * actualimagecursor.getString(actual_image_column_index); return img_path;
	 * }
	 */
	
	/**
	 * get a bitmap file from asset folder
	 * 
	 * @param url
	 * @return
	 */
	public static Bitmap getBitmapFromAsset1(Context mContext,String filename) {
		String url2 = "";
		Bitmap image = null;
		AssetManager am = mContext.getResources().getAssets();  
		  try  
		  {  
		      InputStream is = am.open(filename);  
		      image = BitmapFactory.decodeStream(is);  
		      is.close();  
		  }  
		  catch (IOException e)  
		  {  
		      e.printStackTrace();  
		  }  
		
		
		return image;
	}
	
	/**
	 * get a bitmap file from asset folder
	 * 
	 * @param url
	 * @return
	 */
	public static Bitmap getBitmapFromResources(Context mContext,int drawID) {

		return BitmapFactory.decodeResource(mContext.getResources(), drawID);
	}
	
	
	public static String getFilePathFromAppSDCard(Context mContext,String filename) {
		File storage = null;
		if (checkSDCardAvailable()) {
			storage = android.os.Environment.getExternalStorageDirectory();
		}else
		{
			storage = mContext.getFilesDir();
		}
		
		String path = 
				storage.getAbsolutePath()+ File.separator+ConstantData.SDCARDFOLDER 
				+ File.separator+ filename;
				
			
		return path;
	}
	/**
	 * get a bitmap file from app folder (/sdcard/healthbox)
	 * @param url
	 * @return
	 */
	public static Bitmap getBitmapFromAbsolutePathAndName(Context mContext,String url) {
		String url2="";
		Uri u = Uri.parse(url);
		url2 = getRealPathFromURI(mContext,u);
		FileInputStream fis;
		try {
			fis = new FileInputStream(url2);
		} catch (FileNotFoundException e) {
			
			e.printStackTrace();
			return null;
		}
		return BitmapFactory.decodeStream(fis);
	}

	/**
	 * Check the SD card 
	 * @return
	 */
	public static boolean checkSDCardAvailable(){
		boolean isSDAvaialbe = 
				android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);;
		SharedPreferencesUtil sp = SharedPreferencesUtil.getInstance(null);
		if (sp!=null)
		{
			String location = sp.getStorage_location();
			if ((location == null)||(location.length() == 0))
			{
				if (isSDAvaialbe)
				{
					sp.setStorage_location("External");
					return isSDAvaialbe;
				}else
				{
					sp.setStorage_location("Internal");
					return isSDAvaialbe;
				}
			}else
			{
				if (sp.getStorage_location().equals("External"))
				{
					if (isSDAvaialbe)
					{
						return true;
					}else
					{
						return false;
					}
				}else
				{
					if (isSDAvaialbe)
					{
						return false;
					}else
					{
						return false;
					}
				}
			}
		}else
		{
			return isSDAvaialbe;
		}
	}
	
	/**
	 * Get image from SD card by path and the name of image
	 * @param fileName
	 * @return
	 */
	public static File findPhotoFromSDCard(String path,String photoName){
				
		if (checkSDCardAvailable()) {
			File temp = new File(path + File.separator + photoName);
			if (temp.exists())
			{
				return temp;
			}else
				return null;
			
		}else {
			return null;
		}
	}
	/**
	 * Save image to the SD card according to absolute path
	 * @param photoBitmap
	 * @param photoName
	 * @param path
	 */
	public static void savePhotoToAppSDCard(Context mContext, Bitmap photoBitmap,String photoName){
		File storage = null;
		if (checkSDCardAvailable()) {
			storage = android.os.Environment.getExternalStorageDirectory();
		}else
		{
			storage = mContext.getFilesDir();
		}
			File external = storage ;
			savePhotoToAbsolutePath(photoBitmap,external.getAbsolutePath()+File.separator+ ConstantData.SDCARDFOLDER,photoName);
		
	}
	
	public static void createSDFolder(Context context)
	{
		File storage;
		if (checkSDCardAvailable()) {
			storage = android.os.Environment.getExternalStorageDirectory();
		}else
		{
			storage = context.getFilesDir();
		}
		
		String foldername = storage.getAbsolutePath()+ File.separator+ConstantData.SDCARDFOLDER;
		if(!(new File(foldername).isDirectory()))
		{
			new File(foldername).mkdir();
		}
		
	}
	/**
	 * Save image to the SD card according to app folder (/sdcard/healthbox)
	 * @param photoBitmap
	 * @param photoName
	 * @param path
	 */
	public static void savePhotoToAbsolutePath(Bitmap photoBitmap,String path,String photoName){
		if (checkSDCardAvailable()) {
			File dir = new File(path);
			if (!dir.exists()){
				dir.mkdirs();
			}
			
			File photoFile = new File(path , photoName);
			FileOutputStream fileOutputStream = null;
			try {
				fileOutputStream = new FileOutputStream(photoFile);
				if (photoBitmap != null) {
					if (photoBitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream)) {
						fileOutputStream.flush();

					}
				}
			} catch (FileNotFoundException e) {
				photoFile.delete();
				e.printStackTrace();
			} catch (IOException e) {
				photoFile.delete();
				e.printStackTrace();
			} finally{
				try {
					if (fileOutputStream!=null)
						fileOutputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		} 
	}
	
	/**
	 * Delete the image from SD card
	 * @param context
	 * @param path
	 * file:///sdcard/temp.jpg
	 */
	public static void deleteAllPhoto(String path){
		if (checkSDCardAvailable()) {
			File folder = new File(path);
			File[] files = folder.listFiles();
			for (int i = 0; i < files.length; i++) {
				files[i].delete();
			}
		}
	}
	
	public static void deletePhotoAtPathAndName(String path,String fileName){
		if (checkSDCardAvailable()) {
			File folder = new File(path);
			File[] files = folder.listFiles();
			for (int i = 0; i < files.length; i++) {
				if (files[i].getName().split("\\.")[0].equals(fileName)) {
					files[i].delete();
				}
			}
		}
	}
	public static String refFormatNowDate(Long millis) {
		  if ((millis == null))
			  return "NULL";
		  Date nowTime = new Date(millis.longValue());
		  
		  SimpleDateFormat sdFormatter = new SimpleDateFormat("yyyy-MM-dd",Locale.CHINA); 
		  String retStrFormatNowDate = sdFormatter.format(nowTime);

		  return retStrFormatNowDate;
	}
	
	/**
	 * get a bitmap file from app folder (/sdcard/healthbox)
	 * @param url
	 * @return
	 */
	public static Bitmap getHeadFromAppSDCard(Context mContext,String filename,String personID,String sex) {

		Bitmap image = null;
		if ((filename==null)||(filename.length() == 0))
			filename = ConstantData.DEFAULT_HEAD_ICON_MALE;
		
		if (filename.equals(ConstantData.DEFAULT_HEAD_ICON_MALE))
			image = URIConverter.getBitmapFromResources(mContext,R.drawable.bighead);
		else if (filename.equals(ConstantData.DEFAULT_HEAD_ICON_FEMALE))
			image = URIConverter.getBitmapFromResources(mContext,R.drawable.nv_head);
		else if (filename.equals(ConstantData.NoPicture))
		{
			image = URIConverter.getBitmapFromResources(mContext,R.drawable.bighead);			
		}
		else
		{
			File storage = null;
			if (checkSDCardAvailable()) {
				storage = android.os.Environment.getExternalStorageDirectory();
			}else
			{
				storage = mContext.getFilesDir();
			}
			File file = findPhotoFromSDCard(storage.getAbsolutePath()+ File.separator+ConstantData.SDCARDFOLDER, filename);
			if (file!=null)
			{
				FileInputStream fis;
				try {
					fis = new FileInputStream(file);
					image =  BitmapFactory.decodeStream(fis);  
					return image;
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}
			}else
			{
				KuaiPanManager.getInstance(mContext).downloadFile(personID, filename);
			}
			
		}
		if (image == null)
		{
			if (sex.equals("男"))
			{
				image = URIConverter.getBitmapFromResources(mContext,R.drawable.bighead);
			}else
			{
				image = URIConverter.getBitmapFromResources(mContext,R.drawable.nv_head);
			}
		}
		return image;
	}

	public static void deletePictureFromAppSDCard(Context context,String filename) {
		File storage = null;
		if (checkSDCardAvailable()) {
			storage = android.os.Environment.getExternalStorageDirectory();
		}else
		{
			storage = context.getFilesDir();
		}
		File file = findPhotoFromSDCard(storage.getAbsolutePath()+ File.separator+ConstantData.SDCARDFOLDER, filename);
		if (file!=null)
		{
			file.delete();
		}
	}
	public static Bitmap getPictureFromAppSDCard(Context context,
			String personID, String filename) {
		
		Bitmap image = null;
		File storage = null;
		if (checkSDCardAvailable()) {
			storage = android.os.Environment.getExternalStorageDirectory();
		}else
		{
			storage = context.getFilesDir();
		}
		File file = findPhotoFromSDCard(storage.getAbsolutePath()+ File.separator+ConstantData.SDCARDFOLDER, filename);
		if (file!=null)
		{
			FileInputStream fis;
			try {
				fis = new FileInputStream(file);
				image =  BitmapFactory.decodeStream(fis);  
				return image;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else
		{
			KuaiPanManager.getInstance(context).downloadFile(personID, filename);
		}
		return getBitmapFromResources(context, R.drawable.xzz);
	}

	public static Bitmap getDoctorHeadFromAppSDCard(Context context,String docFilename,String sex) 
	{
		Bitmap image = null;
		File storage = null;
		if (checkSDCardAvailable()) {
			storage = android.os.Environment.getExternalStorageDirectory();
		}else
		{
			storage = context.getFilesDir();
		}
		File file = findPhotoFromSDCard(storage.getAbsolutePath()+ 
								File.separator+ConstantData.SDCARDFOLDER, docFilename);
		if (file!=null)
		{
			FileInputStream fis;
			try {
				fis = new FileInputStream(file);
				image =  BitmapFactory.decodeStream(fis);  
				return image;
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		}else
		{
			KuaiPanManager.getInstance(context).downloadFile("", docFilename);
			
		}
		
		if (sex.equals("男"))
		{
			return getBitmapFromResources(context, R.drawable.cartoondoc);
		}else
		{
			return getBitmapFromResources(context, R.drawable.cartoondocfemale);
		}
	}
}
